package com.example.demo.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.example.demo.pojo.param.ParamReadRes;
import com.example.demo.pojo.param.ParamReadRes.Command;
import com.example.demo.pojo.zuwang.autocheck.ZuWangAutoCheckFromJSRes;
import com.example.demo.pojo.zuwang.zuwang.ZuWangFromJSRes;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Component
public class ConfigFileUtil {

    @Value("${dataLoc.params.jicheng}")
    public String param_jicheng_loc;
    @Value("${dataLoc.params.jieshou}")
    public String param_jieshou_loc;
    @Value("${dataLoc.params.remote}")
    public String param_remote_loc;

    @Value("${dataLoc.autoCheck.jicheng}")
    public String autoCheck_jicheng_loc;
    @Value("${dataLoc.autoCheck.jieshou}")
    public String autoCheck_jieshou_loc;
    @Value("${dataLoc.autoCheck.remote}")
    public String autoCheck_remote_loc;



    public ZuWangFromJSRes readDataMonitor(String dateStateFileName) {

        File file = new File(dateStateFileName);
        try {
            if (!file.exists()) {
                return new ZuWangFromJSRes();
            }
            InputStream inputStream = new FileInputStream(file);

            String read = IoUtil.read(inputStream, CharsetUtil.UTF_8);

            if (read != null && read.length() > 0) {

                ZuWangFromJSRes zW = JSONUtil.toBean(read, ZuWangFromJSRes.class);
                return zW;
            }
            return new ZuWangFromJSRes();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public List<ZuWangAutoCheckFromJSRes> readAutoCheck_jieshou() {
        File file = new File(autoCheck_jieshou_loc);
        try {
            if (!file.exists()) {
                return new ArrayList<>();
            }
            InputStream inputStream = new FileInputStream(file);

            String read = IoUtil.read(inputStream, CharsetUtil.UTF_8);

            if (read != null && read.length() > 0) {

                JSONArray objects = JSONUtil.parseArray(read);
                List<ZuWangAutoCheckFromJSRes> list = JSONUtil.toList(objects, ZuWangAutoCheckFromJSRes.class);
                return list;
            }
            return new ArrayList<>();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public List<ZuWangAutoCheckFromJSRes> readAutoCheck_remoteControl() {
        File file = new File(autoCheck_remote_loc);
        try {
            if (!file.exists()) {
                return new ArrayList<>();
            }
            InputStream inputStream = new FileInputStream(file);

            String read = IoUtil.read(inputStream, CharsetUtil.UTF_8);

            if (read != null && read.length() > 0) {

                JSONArray objects = JSONUtil.parseArray(read);
                List<ZuWangAutoCheckFromJSRes> list = JSONUtil.toList(objects, ZuWangAutoCheckFromJSRes.class);
                return list;
            }
            return new ArrayList<>();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public String readParamJson_jieshou() {
        File file = new File(param_jieshou_loc);
        try {
            if (!file.exists()) {
                return "";
            }
            InputStream inputStream = new FileInputStream(file);
            String read = IoUtil.read(inputStream, CharsetUtil.UTF_8);
            return read;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public String readParamJson_remoteControl() {
        File file = new File(param_remote_loc);
        try {
            if (!file.exists()) {
                return "";
            }
            InputStream inputStream = new FileInputStream(file);
            String read = IoUtil.read(inputStream, CharsetUtil.UTF_8);
            return read;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 任何文件都需要遍历取出自己的东西 然后保存
     *
     * @param filename
     * @param object
     */
    public static void saveFile(String filename, Object object) {

        try {
            // 创建一个FileOutputStream对象，‌指向要写入的文件
            FileOutputStream fos = new FileOutputStream(filename);

            OutputStreamWriter writer = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
            writer.write(JSONUtil.toJsonStr(object));
            writer.close();
            fos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static ParamReadRes parseCommand(String command) throws Exception {

        ParamReadRes paramReadRes = new ParamReadRes();
        //反射赋值
        Class clsC = Class.forName("com.example.demo.pojo.param.ParamReadRes$Command");
        Command obj = (Command) clsC.newInstance();// new User();

        String[] splits = command.split(",");
        for (int i = 0; i < splits.length; i++) {
            String ls = splits[i];//取出来的字符串
            Field[] fields = clsC.getDeclaredFields();
            for (Field field : fields) {
                if (ls.equals(field.getName())) {
                    field.setAccessible(true);
                    //获取字段的值
                    String value = splits[++i];
                    if (ls.equals("SETNET")) {

                        String value2 = splits[++i];
                        obj.setSETNET(value + "," + value2);

                    } else if (ls.equals("FREQ")) {
                        StringBuilder sb = new StringBuilder();
                        for (int j = i + 1; j < splits.length; j++) {
                            sb.append(splits[j]);
                            sb.append(",");
                        }
                        obj.setFREQ(sb.toString());
                    } else {

                        field.set(obj, value);
                        break;
                    }

                }

            }
        }
        paramReadRes.setCommand(obj);
        return paramReadRes;
    }

    public static ParamReadRes parseConverter(ParamReadRes paramReadRes, String converter) throws Exception {

        /**
         * "converter":	"<Count,2,
         *
         * Port1,devMode,0,devType,0,baudrate,115200,databit,8,parity,0,stopbit,1,flowControl,0,dev,/dev/ttymxc2,
         *
         * Port2,devMode,0,devType,0,baudrate,115200,databit,8,parity,0,stopbit,1,flowControl,0,dev,/dev/ttymxc3,
         *
         * Socket
         * ,serverAddr1,118.190.175.215,serverPort1,10099,serverAddr2,,serverPort2,0,serverAddr3,,serverPort3,0,serverAddr4,,serverPort4,0,serverAddr5,,serverPort5,0,serverAddr6,,serverPort6,0>\r\n",
         * 	"transtype":	"1004"
         * }
         */
        String[] s1 = converter.split(",Port2");
        String port1Str = s1[0];
        String[] s2 = s1[1].split("Socket");
        String port2Str = s2[0];
        String serverPortStr = s2[1];


        Class clsCon = Class.forName("com.example.demo.pojo.param.ParamReadRes$Converter");
        ParamReadRes.Converter port1 = (ParamReadRes.Converter) clsCon.newInstance();// new User();
        ParamReadRes.Converter port2 = (ParamReadRes.Converter) clsCon.newInstance();// new User();

        Class clsS = Class.forName("com.example.demo.pojo.param.ParamReadRes$ServerInfo");
        ParamReadRes.ServerInfo serverInfo = (ParamReadRes.ServerInfo) clsS.newInstance();// new User();

        String[] splits1 = port1Str.split(",");
        for (int i = 0; i < splits1.length; i++) {
            String ls = splits1[i];//取出来的字符串
            Field[] fields = clsCon.getDeclaredFields();
            for (Field field : fields) {
                if (ls.equals(field.getName())) {
                    field.setAccessible(true);
                    //获取字段的值
                    String value = splits1[++i];
                    field.set(port1, value);
                    break;

                }
            }
        }
        paramReadRes.setPort1(port1);


        String[] splits2 = port2Str.split(",");
        for (int i = 0; i < splits2.length; i++) {
            String ls = splits2[i];//取出来的字符串
            Field[] fields = clsCon.getDeclaredFields();
            for (Field field : fields) {
                if (ls.equals(field.getName())) {
                    field.setAccessible(true);
                    //获取字段的值
                    String value = splits2[++i];
                    field.set(port2, value);
                    break;

                }
            }
        }
        paramReadRes.setPort1(port1);


        String[] splits3 = serverPortStr.split(",");
        for (int i = 0; i < splits3.length; i++) {
            String ls = splits3[i];//取出来的字符串
            Field[] fields = clsS.getDeclaredFields();
            for (Field field : fields) {
                if (ls.equals(field.getName())) {
                    field.setAccessible(true);
                    //获取字段的值
                    String value = splits3[++i];
                    field.set(serverInfo, value);
                    break;

                }
            }
        }
        paramReadRes.setPort1(port1);
        paramReadRes.setPort2(port2);
        paramReadRes.setServerInfo(serverInfo);

        return paramReadRes;
    }
}
